package org.csu.mypetstore.controller;

//import jakarta.validation.constraints.Pattern;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Objects;

@Controller
@Validated
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    //private PasswordEncoder passwordEncoder;

    /*@PostMapping("/register")
    @CrossOrigin(origins = "http://localhost:5173")
    public Result register(@Pattern(regexp = "^\\${4,16}") String username,@Pattern(regexp = "^\\${4,16}") String password){
        //查询用户
        Account account = accountService.findByAccountname(username);
        if (account==null){
            //register
            accountService.register(username,password);
            return Result.success();
        }else{
            return  Result.error("用户名已被占用");
        }
    }*/
    @GetMapping("/loginView")
    public String loginView(Model model){
        model.addAttribute("account", new Account());
        return "account/signOn";
    }


    @PostMapping("/register")
    public String register(@ModelAttribute Account account, Model model){
        model.addAttribute("account", new Account());
        // 检查用户名是否已存在
        if (accountService.getAccount(account.getUsername())!=null) {
            model.addAttribute("error message","用户名已存在");
            return "redirect:/account/register"; // 返回错误页面
        }


        // 进行账户注册
        accountService.insertAccount(account);
        //List<Category> catagroyList = catalogService.getCategoryList();
        //List<String> idList = catagroyList.stream()
                //.map(Category::getCategoryId)
                //.collect(Collectors.toList());
        //model.addAttribute("idList",idList);
        model.addAttribute("success message", "注册成功，请登录");
        return "account/signOn";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) {
        Account account = accountService.getAccount(username,password);
        System.out.println(account);
        //判断密码是否正确
        if(account!=null){
                System.out.println(account.getUsername());
                model.addAttribute("username",username);
                session.setAttribute("username",username);
                session.setAttribute("account",account);
                model.addAttribute("success message login","登录成功");
                return "redirect:/catalog/main";
        }
        model.addAttribute("error message login" ,"用户名错误或者不存在，请重试");
        return  "account/signOn";
    }

    @GetMapping("/userInfo")
    public Account userInfo(Model model){
        String username = (String)model.getAttribute("username");
        Account account = accountService.getAccount(username);
        model.addAttribute("account",account);
        return account;
    }
    @GetMapping("/userInfoView")
    public String userInfoView(Model model,HttpSession session){

        String username = (String)session.getAttribute("username");
        //System.out.println((String)session.getAttribute("username"));
        if(username!=null) {
            Account account = accountService.getAccount(username);
            System.out.println(account);
            model.addAttribute("account", account);
            return "account/update";
        }
        System.out.println("username null");
        return "catalog/main";
    }


    @PutMapping("/updatePsd")
    public  String updatePsd(@RequestBody String password,String repassword,Model model){

        if(Objects.equals(password, repassword)){
            String username = (String)model.getAttribute("username");
            Account account = accountService.getAccount(username);
            account.setPassword(password);
            model.addAttribute("success message updatePsd","密码重置成功");
            accountService.updatePsd(account);
            return "redirect:/account/updatePsd";
        }
        model.addAttribute("error message updatePsd","密码不一致");
    return "redirect:/account/updatePsd";
    }

    @PutMapping("/update")
    public String update(@RequestBody Account account ,Model model){
        accountService.updateAccount(account);
        model.addAttribute("success message","用户信息修改成功");
        return "redirect:/account/update";
    }

    @GetMapping("/logout")
    public String logout(Model model,HttpSession session){
        model.addAttribute("username",null);
        session.setAttribute("username",null);
        model.addAttribute("account", null);
        session.setAttribute("account",null);
        return "redirect:/catalog/main";
    }
    @GetMapping("/registerView")
    public String registerView(Model model){
        model.addAttribute("account", new Account());
        return "account/register";
    }



}

/*@PostMapping("/login")
@CrossOrigin(origins = "http://localhost:5173")
public String login(@Pattern(regexp = "^\\${5,16}")String username,@Pattern(regexp = "^\\${5,16}")String password){
    //根据用户名查询用户
    Account account = accountService.findByAccountname(username);
    //判断是否存在
    if(account==null){
        //return Result.error("username error");
        return "account/login";
    }else{

    }
    //判断密码是否正确
    if(passwordEncoder.matches(password, account.getPassword())){
        //登录成功
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", account.getUsername());
        //String token = JwtUtil.genToken(claims);
        //return Result.success(token);
        return "catalog/main";
    }else{
        return "account/login";
    }
}*/

/*@GetMapping("/userInfo")
@CrossOrigin(origins = "http://localhost:5173")
public Result<Account> uerInfo(*//*@RequestHeader(name ="Authorization")String token*//*){
    //根据token中的用户名查询用户
        *//*Map<String,Object> map = JwtUtil.parseToken(token);
        String username = (String)map.get("username");*//*
    Map<String,Object>map = ThreadLocalUtil.get();
    String username = (String)map.get("username");
    Account account = accountService.findByAccountname(username);
    return Result.success(account);
}*/


/*@PutMapping("/update")
@CrossOrigin(origins = "http://localhost:5173")
public Result upDate(@RequestBody Account account ){
    accountService.update(account);
    return Result.success();
}*/


/*@PatchMapping("/updatePwd")
@CrossOrigin(origins = "http://localhost:5173")
public Result updatePwd(@RequestBody Map<String,String>params){
    //1.参数检验
    String oldPwd = params.get("old_psd");
    String newPwd = params.get("new_pwd");
    String rePwd = params.get("re_pwd");
    if(!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)||!StringUtils.hasLength(rePwd)){
        return  Result.error("缺少输入内容");
    }
    //效验
    Map<String,Object> map = ThreadLocalUtil.get();
    String username = (String)map.get("username");
    Account account = accountService.findByAccountname(username);
    String encryptedPassword = passwordEncoder.encode(oldPwd);
    if(!account.getPassword().equals(encryptedPassword)){
        return Result.error("密码错误");
    }
    if(!rePwd.equals(newPwd)){
        return Result.error("前后两次密码不一致");
    }
    accountService.updatePwd(newPwd);
    return Result.success();

}*/




